using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using wx.web.Models;

namespace wx.web.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 首页 - 自动检测登录状态
        /// </summary>
        public IActionResult Index()
        {
            var openId = HttpContext.Session.GetString("wechat_openid");

            if (string.IsNullOrEmpty(openId))
            {
                // 未登录，跳转到微信授权
                var returnUrl = Url.Action("Index", "Home", null, Request.Scheme)!;
                return RedirectToAction("Authorize", "WeChat", new { returnUrl });
            }

            ViewBag.OpenId = openId;
            ViewBag.Nickname = HttpContext.Session.GetString("wechat_nickname");
            ViewBag.HeadImgUrl = HttpContext.Session.GetString("wechat_headimgurl");

            return View();
        }

        /// <summary>
        /// 用户个人资料页面（需要用户信息授权）
        /// </summary>
        public IActionResult Profile()
        {
            var openId = HttpContext.Session.GetString("wechat_openid");
            if (string.IsNullOrEmpty(openId))
            {
                // 未登录，跳转到用户信息授权
                var returnUrl = Url.Action("Profile", "Home", null, Request.Scheme)!;
                return RedirectToAction("AuthorizeUserInfo", "WeChat", new { returnUrl });
            }

            var scope = HttpContext.Session.GetString("wechat_scope");
            if (scope != "snsapi_userinfo")
            {
                // 当前是静默授权，需要重新授权获取用户信息
                var returnUrl = Url.Action("Profile", "Home", null, Request.Scheme)!;
                return RedirectToAction("AuthorizeUserInfo", "WeChat", new { returnUrl });
            }

            ViewBag.OpenId = openId;
            ViewBag.Nickname = HttpContext.Session.GetString("wechat_nickname");
            ViewBag.HeadImgUrl = HttpContext.Session.GetString("wechat_headimgurl");
            ViewBag.UnionId = HttpContext.Session.GetString("wechat_unionid");

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
